﻿using Nuwanda.Common;
using System.Threading;
using Nuwanda.TfsSpotlight.Shell.Services.Interfaces;
using StructureMap;
using System.Diagnostics;

namespace Nuwanda.TfsSpotlight.Shell.Services
{
    [Author("Bartłomiej Legiędź")]
    [Pluggable("Worker")]
    public class Worker : IWorker
    {
        private readonly ManualResetEvent _workDone;

        public bool IsWorking
        {
            get { return !this._workDone.WaitOne(1, false); }
        }

        public Worker()
        {
            this._workDone = new ManualResetEvent(true);
        }

        /// <summary>Begins an asynchronous work</summary>
        /// <returns>True if the work was started</returns>
        public bool BeginWork()
        {
            if (!this._workDone.WaitOne(1, false))
            {
                Debug.WriteLine("BeginWork failed to start...");
                return false;
            }

            this._workDone.Reset();
            return true;
        }

        /// <summary>Begins an asynchronous work</summary>
        /// <returns>True if the work was started</returns>
        public void WaitAndBeginWork()
        {
            this._workDone.WaitOne();
            this._workDone.Reset();
        }

        /// <summary>Ends asynchronous work</summary>
        public void EndWork()
        {
            this._workDone.Set();
        }

        /// <summary>Waits till the end of current work</summary>
        public void WaitTillEnd()
        {
            this._workDone.WaitOne();
        }
    }
}